package com.example.javaairportflightanalysis.service.impl;

import com.example.javaairportflightanalysis.comparator.GenericComparator;
import com.example.javaairportflightanalysis.dao.HomePageMapepr;
import com.example.javaairportflightanalysis.domin.HomePageNonstop;
import com.example.javaairportflightanalysis.domin.HomePageTransfer;
import com.example.javaairportflightanalysis.service.HomePageService;
import com.example.javaairportflightanalysis.utils.GroupAndPageUtil;
import com.github.pagehelper.PageInfo;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author shen
 */
@Service
@Slf4j
public class HomePageServiceImpl implements HomePageService {
    @Resource
    HomePageMapepr homePageMapepr;

    @Override
    public PageInfo homePageAList(Integer pageNum, Integer pageSize) throws ParseException {
        List<HomePageNonstop> homePageNonstops = homePageMapepr.selectAllNonstopA();
        homePageNonstops = new ArrayList<>(homePageNonstops.stream()
                // 过滤掉 fptt 为空或者 null 的
//                .filter(h -> h.getFptt() != null && !h.getFptt().isEmpty())
                // 用 dfltFlid 作为 key，如果有重复的，只保留最后一个
                .collect(Collectors.toMap(HomePageNonstop::getDfltFlid, Function.identity(), (a, b) -> b))
                .values());
        List<HomePageNonstop> beforeList = getBeforeList(homePageNonstops);
        for (HomePageNonstop homePageNonstop : beforeList) {
            if (homePageNonstop.getFlag()==2){
                log.info("取消的航班：{}",homePageNonstop);
            }
        }
        PageInfo pageInfo = GroupAndPageUtil.getPageInfo(beforeList, pageNum, pageSize);
        return pageInfo;
    }

    @Override
    public PageInfo homePageDList(Integer pageNum, Integer pageSize) throws ParseException {
        List<HomePageNonstop> homePageNonstops = homePageMapepr.selectAllNonstopD();
        homePageNonstops = new ArrayList<>(homePageNonstops.stream()
                // 过滤掉 fptt 为空或者 null 的
//                .filter(h -> h.getFptt() != null && !h.getFptt().isEmpty())
                // 用 dfltFlid 作为 key，如果有重复的，只保留最后一个
                .collect(Collectors.toMap(HomePageNonstop::getDfltFlid, Function.identity(), (a, b) -> b))
                .values());


        List<HomePageNonstop> beforeList = getBeforeList(homePageNonstops);

//        for (HomePageNonstop homePageNonstop : beforeList) {
//            if (homePageNonstop.getFlag()==2){
//                log.info("取消的航班：{}",homePageNonstop);
//            }
//        }
        PageInfo pageInfo = GroupAndPageUtil.getPageInfo(beforeList, pageNum, pageSize);
        return pageInfo;
    }

    /**
     * 这个是直达情况集中处理特殊情况
     */
    private List<HomePageNonstop> getBeforeList(List<HomePageNonstop> homePageNonstops) throws ParseException {
        Collections.sort(homePageNonstops, new GenericComparator<>());

        for (HomePageNonstop homePageNonstop : homePageNonstops) {
            homePageNonstop.setFlag(0);
            if (StringUtils.isNotBlank(homePageNonstop.getFrtt())) {
                String date1 = GroupAndPageUtil.getDate(homePageNonstop.getFrtt());
                homePageNonstop.setFrtt(date1);
            } else {
                homePageNonstop.setFrtt("暂未起飞");
            }
            //这种情况是Iars和Fett都不为空，需要把Fett赋值给
            if (StringUtils.isNotBlank(homePageNonstop.getIars()) || StringUtils.isNotBlank(homePageNonstop.getFett())) {
                //flag 1为延误
                homePageNonstop.setFlag(1);
                String date = GroupAndPageUtil.getDate(homePageNonstop.getFett());
                homePageNonstop.setFptt(date);
                homePageNonstop.setFett(date);
            } else if (StringUtils.isNotBlank(homePageNonstop.getAbst())) {
                //flag2为取消
                homePageNonstop.setFlag(2);
            }
        }
        return homePageNonstops;
    }

    @Override
    public PageInfo homePageTransferListA(Integer pageNum, Integer pageSize) throws ParseException {
        List<HomePageTransfer> homePageTransfers = homePageMapepr.selectAllTransferA();
        homePageTransfers = new ArrayList<>(homePageTransfers.stream()

                // 用 dfltFlid 作为 key，如果有重复的，只保留最后一个
                .collect(Collectors.toMap(HomePageTransfer::getDfltFlid, Function.identity(), (a, b) -> b))
                .values());

        List<HomePageTransfer> beforeTransferPageInfo = getBeforeTransferPageInfo(homePageTransfers);
        return GroupAndPageUtil.getPageInfo(beforeTransferPageInfo, pageNum, pageSize);
    }

    @Override
    public PageInfo homePageTransferListD(Integer pageNum, Integer pageSize) throws ParseException {
        List<HomePageTransfer> homePageTransfers = homePageMapepr.selectAllTransferD();
        homePageTransfers = new ArrayList<>(homePageTransfers.stream()
                // 过滤掉 fptt 为空或者 null 的
//                .filter(h -> h.getFptt() != null && !h.getFptt().isEmpty())
                // 用 dfltFlid 作为 key，如果有重复的，只保留最后一个
                .collect(Collectors.toMap(HomePageTransfer::getDfltFlid, Function.identity(), (a, b) -> b))
                .values());
        List<HomePageTransfer> beforeTransferPageInfo = getBeforeTransferPageInfo(homePageTransfers);
        return GroupAndPageUtil.getPageInfo(beforeTransferPageInfo, pageNum, pageSize);

    }


    /**
     * 这个是中转站的直达情况集中处理特殊情况
     */
    private List<HomePageTransfer> getBeforeTransferPageInfo(List<HomePageTransfer> homePageTransfers) throws ParseException {
        Collections.sort(homePageTransfers, new GenericComparator<>());
        for (HomePageTransfer homePageTransfer : homePageTransfers) {
            //截取成三个城市
            String substring = homePageTransfer.getApcd().substring(0, 3);
            homePageTransfer.setApcd(substring+homePageTransfer.getTransitApcd());
            //截取时间成预计时间
            String subString = homePageTransfer.getFptt().substring(0, 19);
            homePageTransfer.setFptt(subString);
            homePageTransfer.setFlag(0);
            //实际起飞时间不为空
            if (StringUtils.isNotBlank(homePageTransfer.getFrtt())) {
                String date1 = GroupAndPageUtil.getDate(homePageTransfer.getFrtt());
                homePageTransfer.setFrtt(date1);
            }else {
                homePageTransfer.setFrtt("暂未起飞");
            }
            //这种情况是Iars和Fett都不为空，需要把Fett赋值给
            if (StringUtils.isNotBlank(homePageTransfer.getIars()) && StringUtils.isNotBlank(homePageTransfer.getFett())) {
                //flag 1为取消
                homePageTransfer.setFlag(1);
            } else if (StringUtils.isNotBlank(homePageTransfer.getAbst())) {
                //flag2为延误
                homePageTransfer.setFlag(2);
                if (StringUtils.isNotBlank(homePageTransfer.getFett())) {
                    String date = GroupAndPageUtil.getDate(homePageTransfer.getFett());
                    homePageTransfer.setFptt(date);
                }
            }
        }
       return homePageTransfers;
    }

    @Override
    public PageInfo selectHomePageA(String dfltFlno, String dtime, Integer pageNum, Integer pageSize) throws ParseException {
        List<HomePageNonstop> homePageNonstops = homePageMapepr.selectAllNonstopA();
        String finalDtime = formatDate(dtime,true);
        homePageNonstops = new ArrayList<>(homePageNonstops.stream()
                // 过滤掉 fptt 为空或者 null 的
                .filter(h -> h.getFptt() != null && !h.getFptt().isEmpty())
                // 用 dfltFlid 作为 key，如果有重复的，只保留最后一个
                .collect(Collectors.toMap(HomePageNonstop::getDfltFlid, Function.identity(), (a, b) -> b))
                .values());
        List<HomePageNonstop> beforeNonstopPageInfo = getBeforeList(homePageNonstops);

        Predicate<HomePageNonstop> predicate = Nonstop -> true;
        if (!Objects.isNull(dfltFlno)) {
            predicate = predicate.and(Nonstop -> Nonstop.getDfltFlno().contains(dfltFlno));
        }
        if (!StringUtils.isEmpty(finalDtime)) {
            log.info("=================");
            log.info("dtime:{}", finalDtime);
            predicate = predicate.and(Nonstop -> Nonstop.getDtime().contains(finalDtime));
        }
        List<HomePageNonstop> result = beforeNonstopPageInfo.stream()
                .filter(predicate)
                .toList();
        log.info("result:{}", result);
        return  GroupAndPageUtil.getPageInfo(result, pageNum, pageSize);
    }

    @Override
    public PageInfo selectHomepageTransferA(String dfltFlno, String dtime, Integer pageNum, Integer pageSize) throws ParseException {
        List<HomePageTransfer> homePageTransfers = homePageMapepr.selectAllTransferA();
        String finalDtime = formatDate(dtime,true);
        homePageTransfers = new ArrayList<>(homePageTransfers.stream()
                // 过滤掉 fptt 为空或者 null 的
                .filter(h -> h.getFptt() != null && !h.getFptt().isEmpty())
                // 用 dfltFlid 作为 key，如果有重复的，只保留最后一个
                .collect(Collectors.toMap(HomePageTransfer::getDfltFlid, Function.identity(), (a, b) -> b))
                .values());
        List<HomePageTransfer> beforeTransferPageInfo = getBeforeTransferPageInfo(homePageTransfers);

        Predicate<HomePageTransfer> predicate = transfer -> true;
        if (!Objects.isNull(dfltFlno)) {
            predicate = predicate.and(transfer -> transfer.getDfltFlno().contains(dfltFlno));
        }
        if (!StringUtils.isEmpty(finalDtime)) {
            log.info("=================");
            log.info("dtime:{}", finalDtime);
            predicate = predicate.and(transfer -> transfer.getDtime().contains(finalDtime));
        }
        List<HomePageTransfer> result = beforeTransferPageInfo.stream()
                .filter(predicate)
                .toList();
        log.info("result:{}", result);
        return  GroupAndPageUtil.getPageInfo(result, pageNum, pageSize);
    }

    @Override
    public PageInfo selectHomePageD(String dfltFlno, String dtime, Integer pageNum, Integer pageSize) throws ParseException {
        List<HomePageNonstop> homePageNonstops = homePageMapepr.selectAllNonstopD();
        String finalDtime = formatDate(dtime,true);
        homePageNonstops = new ArrayList<>(homePageNonstops.stream()
                // 过滤掉 fptt 为空或者 null 的
                .filter(h -> h.getFptt() != null && !h.getFptt().isEmpty())
                // 用 dfltFlid 作为 key，如果有重复的，只保留最后一个
                .collect(Collectors.toMap(HomePageNonstop::getDfltFlid, Function.identity(), (a, b) -> b))
                .values());
        List<HomePageNonstop> beforeNonstopPageInfo = getBeforeList(homePageNonstops);

        Predicate<HomePageNonstop> predicate = Nonstop -> true;
        if (!Objects.isNull(dfltFlno)) {
            predicate = predicate.and(Nonstop -> Nonstop.getDfltFlno().contains(dfltFlno));
        }
        if (!StringUtils.isEmpty(finalDtime)) {
            log.info("=================");
            log.info("dtime:{}", finalDtime);
            predicate = predicate.and(Nonstop -> Nonstop.getDtime().contains(finalDtime));
        }
        List<HomePageNonstop> result = beforeNonstopPageInfo.stream()
                .filter(predicate)
                .toList();
        log.info("result:{}", result);
        return  GroupAndPageUtil.getPageInfo(result, pageNum, pageSize);
    }

    @Override
    public PageInfo selectHomePageTransferD(String dfltFlno, String dtime,  Integer pageNum, Integer pageSize) throws ParseException {
        List<HomePageTransfer> homePageTransfers = homePageMapepr.selectAllTransferD();
        String finalDtime = formatDate(dtime,true);
        homePageTransfers = new ArrayList<>(homePageTransfers.stream()
                // 过滤掉 fptt 为空或者 null 的
                .filter(h -> h.getFptt() != null && !h.getFptt().isEmpty())
                // 用 dfltFlid 作为 key，如果有重复的，只保留最后一个
                .collect(Collectors.toMap(HomePageTransfer::getDfltFlid, Function.identity(), (a, b) -> b))
                .values());
        List<HomePageTransfer> beforeTransferPageInfo = getBeforeTransferPageInfo(homePageTransfers);

        Predicate<HomePageTransfer> predicate = transfer -> true;
        if (!Objects.isNull(dfltFlno)) {
            predicate = predicate.and(transfer -> transfer.getDfltFlno().contains(dfltFlno));
        }
        if (!StringUtils.isEmpty(finalDtime)) {
            log.info("=================");
            log.info("dtime:{}", finalDtime);
            predicate = predicate.and(transfer -> transfer.getDtime().contains(finalDtime));
        }
        List<HomePageTransfer> result = beforeTransferPageInfo.stream()
                .filter(predicate)
                .toList();
        log.info("result:{}", result);
        return  GroupAndPageUtil.getPageInfo(result, pageNum, pageSize);
    }

    private String formatDate(String dateTime, boolean checkParamName) {
        //如果参数为空，就返回一个空字符串
        if (dateTime == null || dateTime.isEmpty()) {
            return "";
        }
        //如果参数不为空，就进行以下操作
        else {
            //解析参数为一个ZonedDateTime对象，它表示一个带有时区信息的日期时间
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTime, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            //将ZonedDateTime对象转换为一个指定时区的ZonedDateTime对象，这里使用东八区（北京时间）
            ZonedDateTime beijingTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
            if (checkParamName) {
                //将ZonedDateTime对象格式化为一个字符串，使用指定的格式
                String formatted = beijingTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
                //返回格式化后的字符串
                return formatted;
            } else {
                //将ZonedDateTime对象格式化为一个字符串，使用指定的格式
                String formatted = beijingTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"));
                //返回格式化后的字符串
                return formatted;
            }
        }
    }

}

